package com.example.llm.learn.api.controller;

import com.example.llm.learn.api.dto.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@CrossOrigin(origins = {"http://localhost:5173", "http://127.0.0.1:5500"})
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    private static final String UPLOAD_DIR = "D:\\developer\\uploads"; // 默认在项目根目录下创建 uploads 文件夹
    private static final String DOWNLOAD_URL_IP_PORT = "http://localhost:9981/api"; // 默认在项目根目录下创建 uploads 文件夹

    @PostMapping(value = "/upload")
    public CommonResponse<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResponse.error500("上传失败：文件为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        if (fileName == null || fileName.isEmpty()) {
            return CommonResponse.error500("上传失败：文件名为空");
        }
        String uuidDir = UUID.randomUUID().toString().replace("-", "");
        // 创建上传目录（如果不存在）
        File uploadDir = new File(UPLOAD_DIR + "/" + uuidDir);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (!created) {
                return CommonResponse.error500("上传失败：无法创建上传目录");
            }
        }
        // 构建目标文件路径
        Path targetPath = Paths.get(uploadDir.getPath(), fileName);
        try {
            // 将文件写入到目标路径
            file.transferTo(targetPath.toFile());
            return CommonResponse.ok(DOWNLOAD_URL_IP_PORT + "/file/" + uuidDir + "/" + fileName);
        } catch (IOException e) {
            log.error("上传失败", e);
            return CommonResponse.error500(e.getMessage());
        }
    }

    @GetMapping("/{uuidDir}/{fileName}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable(value = "uuidDir") String uuidDir,
                                                            @PathVariable(value = "fileName") String fileName) {
        try {
            // 构建文件路径
            Path filePath = Paths.get(UPLOAD_DIR + "/" + uuidDir).resolve(fileName).normalize();
            // 检查文件是否存在
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(filePath.toString());
            } catch (FileNotFoundException e) {
                return ResponseEntity.notFound().build();
            }
            InputStreamResource resource = new InputStreamResource(fileInputStream);
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
            // 设置响应头（强制浏览器下载而不是预览）
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
            String contentType = Files.probeContentType(filePath);  // 自动检测文件类型
            if (contentType == null) {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;  // 默认二进制流
            }
            headers.add(HttpHeaders.CONTENT_TYPE, contentType);
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (IOException e) {
            log.error("下载文件异常", e);
            return ResponseEntity.internalServerError().build();
        }
    }

}
